import { forwardRef, useState } from 'react'
import { Button, Form, Input, InputNumber, Select } from 'antd'
import CommonModal from '@/views/ShoppingCart/components/CommonEditModal.tsx'
import { commonFormProps, commonInputProps } from '@/views/ShoppingCart/commonProps.ts'
import { createPgDb, getPgDbList, getPgDetailById } from '@/api/shoppingCart.ts'

const rules = [
  {
    required: true
  }
]

interface DbConfig {
  id: string
  type: string
  host: string
  port: number
  user: string
  database: string
  name: string
}

const DataBaseInfoModal = forwardRef(
  (
    props: {
      onOk: (id: string) => Promise<boolean>
      dbId: string
      forShow?: boolean
    },
    ref
  ) => {
    const [form] = Form.useForm()

    const [dbOptions, setDbOptions] = useState<
      Array<{
        id: string
        label: string
        value: string
        [key: string]: string
      }>
    >([])

    const [activeName, setActiveName] = useState<[string] | null>(null)

    const [activeId, setActiveId] = useState('')

    const disabled = !!props.forShow
    const disable = !!activeId

    const getDbOptions = () => {
      if (props.dbId) {
        console.log('get db')
        setActiveId(props.dbId)

        getPgDetailById(props.dbId).then((res) => {
          form.setFieldsValue({ ...res, password: '******', name: [res.name] })
          setActiveName([res.name])
        })
      }

      getPgDbList({
        page: 1,
        page_size: 9999
      }).then((res) => {
        setDbOptions(
          res.items.map((it: DbConfig) => ({
            ...it,
            label: it.name,
            value: it.name
          }))
        )
      })
    }

    return (
      <CommonModal
        title="数据库连接"
        ref={ref}
        onOpen={getDbOptions}
        onOk={async () => {
          if (props.forShow) {
            return true
          }
          try {
            const values = await form.validateFields()
            if (!disable) {
              await createPgDb({ ...values, name: values.name[0] })
              const res = await getPgDbList({
                page: 1,
                page_size: 1
              })
              const dbId = res.items[0]?.id
              if (dbId) return await props.onOk(dbId)
            } else {
              return await props.onOk(activeId)
            }
            return false
          } catch {
            return false
          }
        }}
        onCancel={() => {
          console.log('取消了')
        }}>
        <Form
          form={form}
          {...commonFormProps}
          validateMessages={{
            required: "'${label}' 是必填字段"
          }}>
          <div className="grid grid-rows-9">
            <div className="flex gap-2">
              <Form.Item name="name" className="flex-1" label="链接名称" rules={rules}>
                <Select
                  value={activeName}
                  mode="tags"
                  disabled={disabled}
                  placeholder="输入并回车可新建"
                  maxCount={1}
                  options={dbOptions}
                  onSelect={(value, option) => {
                    console.log(value, 'DDG')
                    setActiveName([value])
                    if (option.id) {
                      setActiveId(option.id)
                      if (option.type === 'postgresql') {
                        getPgDetailById(option.id).then((res) => {
                          form.setFieldsValue({ ...res, password: '******', name: [res.name] })
                        })
                      }
                    } else {
                      setActiveId('')
                    }
                  }}
                  onDeselect={() => {
                    if (disable) form.resetFields()
                    setActiveId('')
                    setActiveName(null)
                  }}
                />
              </Form.Item>
              <Button type="primary">编辑</Button>
            </div>
            <Form.Item name="database" label="数据库名称" rules={rules}>
              <Input disabled={disabled || disable} {...commonInputProps()} />
            </Form.Item>
            <Form.Item name="user" label="用户名" rules={rules}>
              <Input disabled={disabled || disable} {...commonInputProps()} />
            </Form.Item>
            <Form.Item name="password" label="密码" rules={rules}>
              <Input.Password disabled={disabled || disable} {...commonInputProps('Password')} />
            </Form.Item>
            <Form.Item name="host" label="地址" rules={rules}>
              <Input disabled={disabled || disable} {...commonInputProps()} />
            </Form.Item>
            <Form.Item name="port" label="端口" rules={rules}>
              <InputNumber disabled={disabled || disable} precision={0} />
            </Form.Item>
            <Form.Item name="schema" label="集合" rules={rules}>
              <Input disabled={disabled || disable} {...commonInputProps()} />
            </Form.Item>
          </div>
        </Form>
      </CommonModal>
    )
  }
)

export default DataBaseInfoModal
